package cn.calm.study.hibernate.many2many.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.calm.study.hibernate.many2many.Student;
import cn.calm.study.hibernate.many2many.dao.IMany2ManyDao;

public class Many2ManyDaoImpl extends HibernateDaoSupport implements
		IMany2ManyDao {

	@Override
	public void save(Object object) {
		getHibernateTemplate().merge(object);
	}

	@Override
	public Student loadStudentById(int i) {
		return getHibernateTemplate().get(Student.class, i);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Student> listAllStudent() {
		return getHibernateTemplate().executeFind(new HibernateCallback<List<Student>>() {

			@Override
			public List<Student> doInHibernate(Session session)
					throws HibernateException, SQLException {
				//去掉重复记录加上.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY)
				return session.createCriteria(Student.class).setResultTransformer( 
					     CriteriaSpecification.DISTINCT_ROOT_ENTITY).list();
			}
		});
	}
}
